package com.qfedu.web.servlet;

import cn.dsna.util.images.ValidateCode;
import com.alibaba.druid.util.StringUtils;
import com.qfedu.pojo.User;
import com.qfedu.service.UserService;
import com.qfedu.service.impl.UserServiceImpl;
import com.qfedu.web.common.BaseServlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URLEncoder;
import java.util.Base64;

/**
 * pojo: 简单的java对象
 * 创建者: QF-SUN
 * 创建时间: 2023/4/3 9:05
 * 描述:
 */
@WebServlet("/userservlet")
public class UserServlet extends BaseServlet {
    private UserService userService = new UserServiceImpl();

    protected String logOut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1. 清除session中的用户信息
        req.getSession().invalidate();
        //2. 清除cookie中的数据
        Cookie cookie = new Cookie("userInfo", "");
        cookie.setMaxAge(1);
        cookie.setPath("/");
        cookie.setDomain("localhost");
        resp.addCookie(cookie);
        //3. 跳转到登录页面
        return "redirect:/login.jsp";
    }

    protected String login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String auto = req.getParameter("auto");

        if(StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            return "redirect:/login.jsp?error";
        }
        User user = userService.login(username, password);

        if(user != null){
            System.out.println("登录成功!!!!");
            req.getSession().setAttribute("user", user);
            if("on".equalsIgnoreCase(auto)) {
                //Base64Utils  对数据进行编码;
                //lee#123456
                String str = username +"#" +password;
                String encode = URLEncoder.encode(str, "utf-8");
                //把用户名和密码存储到cookie中
                Cookie cookie = new Cookie("userInfo", encode);
                cookie.setMaxAge(14 * 24 * 60 * 60);
                cookie.setPath("/");
                cookie.setDomain("localhost");
                resp.addCookie(cookie);
            }
            return "redirect:/index.jsp";
        }

        return "redirect:/login.jsp?error";
    }

    protected String register(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String email = req.getParameter("email");
        String gender = req.getParameter("gender");
        if(StringUtils.isEmpty(username) || StringUtils.isEmpty(password)
                ||StringUtils.isEmpty(email) || StringUtils.isEmpty(gender)) {
            return "redirect:/register.jsp";
        }
        //判断用户名是否存在
        boolean b = userService.checkUsername(username);
        if(b) {
            // 用户名存在
            return "redirect:/register.jsp";
        }

        // 注册业务(增)
        boolean isSuccess = userService.register(username, password, email, gender);
        if(isSuccess) {
            //注册成功
            return "redirect:/login.jsp";
        }else {
            // 注册失败
            return "redirect:/register.jsp";
        }



    }


    protected String checkUsername(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        PrintWriter writer = resp.getWriter();
        String username = req.getParameter("username");
        //如果username为，响应前端
        if(username == null || username.length() == 0) {
            return "0";
        }
        //不为空，需判断在数据库中是否存在

        boolean exist = userService.checkUsername(username);
        if(exist){
            return "1";
        }else{
            return "2";
        }

    }

    /**
     * 生成验证码
     * @param req
     * @param resp
     * @return
     * @throws ServletException
     * @throws IOException
     */
    protected String code(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ValidateCode validateCode = new ValidateCode(110, 40, 2, 20);
        //获取验证码
        String code = validateCode.getCode();
        //存储session中
        req.getSession().setAttribute("code",  code);
        //把 验证码写入到 输出流中
        validateCode.write(resp.getOutputStream());

        return null;
    }

    protected String checkCode(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取用户输入的验证码
        String code = req.getParameter("code");
        //从session中获取验证码
        Object obj = req.getSession().getAttribute("code");
        String codeInServer = null;
        if(obj != null){
            codeInServer = (String) obj;
        }

        if(!StringUtils.isEmpty(code) && code.equalsIgnoreCase(codeInServer)){
            return "0";
        }else {
            return "1";
        }
    }

}
